import React, { useState } from 'react';
import { router } from 'expo-router';
import { WhiteSpace } from '@ant-design/react-native';
import { View } from 'react-native';
import ButtonDemo from '@/components/features/device/ButtonDemo';
import { CurrentSceneCard } from '@/components/features/device/CurrentSceneCard';
import ProfileEditor from '@/components/features/device/ProfileEditor';
import { loginUser } from '@/api/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import storage from '@/api/storageType';

export default function BlankScreen() {
    const [profile, setProfile] = useState({
        phone: '',
        password: '',
    });

    const handleSave = async () => {
        try {
            const response = await loginUser({
                username: profile.phone,
                password: profile.password,
            });
            console.log('Login response:', response.data);
            const { access, refresh } = response.data.data;
            await storage.setItem('access_token', access);
            await storage.setItem('refresh_token', refresh);
            console.log('access_token:', access);
            console.log('refresh_token:', refresh);
            alert('登录成功！');
            router.push('/HomePage');
        } catch (error: any) {
            alert('登录失败: ' + (error.response?.data?.error?.message || error.message));
        }
    };

    return (
        <View style={{ flex: 1, backgroundColor: '#fff'}}>
            <View style={{ alignItems: 'center' }}>
                <CurrentSceneCard
                    image={require('../assets/images/loginBackground.png')}
                    title="登录"
                    desc="全家，尽在掌握 =）"
                    inLoginPage={true}
                />
                <ProfileEditor
                    fields={['phone', 'password']}
                    initialPhone={profile.phone}
                    initialPassword={profile.password}
                    onChange={data => setProfile(prev => ({ ...prev, ...data }))}
                />
                <WhiteSpace size='lg'/>
                <WhiteSpace size='lg'/>
                <ButtonDemo
                    onPress={handleSave}
                    text="登录"
                />
                <ButtonDemo
                    onPress={() => router.push('/RegisterPage')}
                    text="注册"
                />
            </View>
        </View>
    );
}

export const options = {
    headerShown: false,
};